package com.li.jiang.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.jiang.mapper.RoleMenuMapper;
import com.li.jiang.obj.dto.UserLoginData;
import com.li.jiang.obj.pojo.Menu;
import com.li.jiang.mapper.MenuMapper;
import com.li.jiang.obj.pojo.RoleMenu;
import com.li.jiang.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.li.jiang.utils.localThread.UserThreadLocal;
import com.li.jiang.utils.redis.RedisUtil;
import com.li.jiang.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 李江
 * @since 2024-04-12
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getMenus() {
        String token = UserThreadLocal.getToken();
        if (redisUtil.hasKey(token)){
            UserLoginData userLoginData = TokenUtil.parseTokenData((String) redisUtil.get(token));

            //从角色菜单关系表中获取menu ids
            LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<RoleMenu>()
                    .eq(RoleMenu::getRid,userLoginData.getRid());
            List<RoleMenu> rmenus = roleMenuMapper.selectList(wrapper);

            List<Long> menuIds;
            if (CollUtil.isEmpty(rmenus)) {
                return Collections.emptyList();
            }
            menuIds = rmenus.stream().map(RoleMenu::getMid).collect(Collectors.toList());
            //从菜单表中获取menu
            List<Menu> menus = menuMapper.selectBatchIds(menuIds);
            if (CollUtil.isEmpty(menus)){
                return Collections.emptyList();
            }
            return menus;
        }
        return Collections.emptyList();
    }
}
